import 'package:flutter/material.dart';
import 'package:flutter_mobx/flutter_mobx.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:katana_router/katana_router.dart';
import 'package:thal/backstage/blueprint/user_print.dart';
import 'package:thal/backstage/control_room/follow_room.dart';
import 'package:thal/backstage/control_room/global_state_provider.dart';
import 'package:thal/backstage/control_room/user_room.dart';
import 'package:thal/backstage/toolkit/utilities/asset_manifest.dart';
import 'package:thal/backstage/toolkit/utilities/color_palette.dart';
import 'package:thal/backstage/toolkit/utilities/dimension_rules.dart';
import 'package:thal/backstage/toolkit/widgets/stage_whisper.dart';
import 'package:thal/playbill/profile_saga/other_profile_production.dart';

part 'follower_following_list_production.page.dart';

/// 关注/粉丝列表页面
@PagePath('/follower-following-list')
class FollowerFollowingListProduction extends StatefulWidget {
  final bool isFollowingList; // true表示关注列表，false表示粉丝列表

  const FollowerFollowingListProduction({
    super.key,
    required this.isFollowingList,
  });

  @pageRouteQuery
  static RouteQuery query({bool isFollowingList = true}) =>
      const _$FollowerFollowingListProductionQuery().call(
        isFollowingList: isFollowingList,
      );

  @override
  State<FollowerFollowingListProduction> createState() =>
      _FollowerFollowingListProductionState();
}

class _FollowerFollowingListProductionState
    extends State<FollowerFollowingListProduction> {
  late UserRoom _userRoom;
  late FollowRoom _followRoom;
  UserPrint? _currentUser;

  @override
  void didChangeDependencies() {
    super.didChangeDependencies();
    _userRoom = GlobalStateProvider.userRoomOf(context);
    _followRoom = GlobalStateProvider.followRoomOf(context);
    _currentUser = _userRoom.fetchCurrentUser();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Container(
        width: double.infinity,
        height: double.infinity,
        decoration: BoxDecoration(
          image: DecorationImage(
            image: AssetImage(AssetManifest.screenBackground),
            fit: BoxFit.cover,
          ),
        ),
        child: SafeArea(
          bottom: false,
          child: Column(
            children: [
              // 顶部标题栏
              _buildHeader(context),

              // 用户列表
              Expanded(
                child: Observer(
                  builder: (_) {
                    if (_currentUser == null) {
                      return _buildEmptyState();
                    }

                    final userList =
                        widget.isFollowingList
                            ? _getFollowingList()
                            : _getFollowersList();

                    if (userList.isEmpty) {
                      return _buildEmptyListState();
                    }

                    return _buildUserList(userList);
                  },
                ),
              ),
            ],
          ),
        ),
      ),
    );
  }

  /// 构建顶部标题栏
  Widget _buildHeader(BuildContext context) {
    return Padding(
      padding: EdgeInsets.symmetric(horizontal: 16.w, vertical: 16.h),
      child: Row(
        children: [
          GestureDetector(
            onTap: () => Navigator.of(context).pop(),
            child: Container(
              width: 40.w,
              height: 40.w,
              decoration: BoxDecoration(
                color: ColorPalette.white.withValues(alpha: 0.5),
                shape: BoxShape.circle,
              ),
              child: Icon(
                Icons.chevron_left_rounded,
                color: ColorPalette.black,
                size: 36.sp,
              ),
            ),
          ),
          Expanded(
            child: Center(
              child: Text(widget.isFollowingList ? 'Following' : 'Followers')
                  .fontSize(24.sp)
                  .textColor(ColorPalette.black)
                  .carterOne(weight: FontWeight.w400),
            ),
          ),
          36.w.widthBox,
        ],
      ),
    );
  }

  /// 获取关注列表
  List<UserPrint> _getFollowingList() {
    if (_currentUser == null) return [];

    final followingIds = _followRoom.fetchFollowingList(_currentUser!.id);
    return followingIds
        .map((id) => _userRoom.fetchUserById(id))
        .where((user) => user != null)
        .cast<UserPrint>()
        .toList();
  }

  /// 获取粉丝列表
  List<UserPrint> _getFollowersList() {
    if (_currentUser == null) return [];

    final followerIds = _followRoom.fetchFollowersList(_currentUser!.id);
    return followerIds
        .map((id) => _userRoom.fetchUserById(id))
        .where((user) => user != null)
        .cast<UserPrint>()
        .toList();
  }

  /// 构建空状态
  Widget _buildEmptyState() {
    return Center(
      child:
          Text(
            'Please login to view the list',
          ).fontSize(16.sp).textColor(ColorPalette.black).arimo(),
    );
  }

  /// 构建空列表状态
  Widget _buildEmptyListState() {
    return Center(
      child:
          Text(
                widget.isFollowingList
                    ? 'You are not following anyone yet'
                    : 'You have no followers yet',
              )
              .fontSize(16.sp)
              .textColor(ColorPalette.black.withValues(alpha: 0.6))
              .arimo(),
    );
  }

  /// 构建用户列表
  Widget _buildUserList(List<UserPrint> users) {
    return Container(
      width: double.infinity,
      margin: EdgeInsets.symmetric(horizontal: 16.w),
      decoration: BoxDecoration(
        color: ColorPalette.white,
        borderRadius: BorderRadius.all(Radius.circular(16.r)),
      ),
      child: ListView.builder(
        padding: EdgeInsets.symmetric(horizontal: 16.w, vertical: 8.h),
        itemCount: users.length,
        itemBuilder: (context, index) {
          final user = users[index];
          return _buildUserItem(user);
        },
      ),
    );
  }

  /// 构建用户项
  Widget _buildUserItem(UserPrint user) {
    // 如果是粉丝列表且当前用户关注了该粉丝，或者如果是关注列表
    final showFollowButton = !widget.isFollowingList || true;

    return GestureDetector(
      onTap: () => _navigateToUserProfile(context, user.id),
      child: Container(
        padding: EdgeInsets.symmetric(vertical: 16.h),
        decoration: BoxDecoration(color: ColorPalette.white),
        child: Row(
          children: [
            // 用户头像
            Container(
              width: 60.w,
              height: 60.w,
              decoration: BoxDecoration(shape: BoxShape.circle),
              child: ClipOval(
                child: Image.asset(user.avatar, fit: BoxFit.cover),
              ),
            ),

            16.w.widthBox,

            // 用户信息
            Expanded(
              child: Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                mainAxisAlignment: MainAxisAlignment.center,
                children: [
                  // 用户名
                  Text(user.username)
                      .fontSize(16.sp)
                      .textColor(ColorPalette.black)
                      .arimo(weight: FontWeight.w600),

                  4.h.heightBox,

                  // 用户签名
                  Text(
                        user.signature,
                        maxLines: 2,
                        overflow: TextOverflow.ellipsis,
                      )
                      .fontSize(12.sp)
                      .textColor(ColorPalette.black.withValues(alpha: 0.6))
                      .arimo(),
                ],
              ),
            ),

            8.w.widthBox,

            // 关注按钮
            if (showFollowButton &&
                _currentUser != null &&
                user.id != _currentUser!.id)
              Observer(
                builder: (_) {
                  final isCurrentlyFollowing = _followRoom.isFollowing(
                    _currentUser!.id,
                    user.id,
                  );

                  return Container(
                    width: 30.w,
                    height: 30.w,
                    decoration: BoxDecoration(
                      image: DecorationImage(
                        image: AssetImage(AssetManifest.followBackground),
                        fit: BoxFit.contain,
                        colorFilter: ColorFilter.mode(
                          isCurrentlyFollowing
                              ? ColorPalette.blue1
                              : ColorPalette.blue1,
                          BlendMode.srcIn,
                        ),
                      ),
                    ),
                    child: Center(
                      child: Icon(
                        isCurrentlyFollowing ? Icons.remove : Icons.add,
                        color:
                            isCurrentlyFollowing
                                ? ColorPalette.white
                                : ColorPalette.white,
                        size: 20.sp,
                      ),
                    ),
                  ).withTapEffect(
                    onTap: () => _toggleFollow(user.id),
                    scaleFactor: 0.7,
                  );
                },
              ),
          ],
        ),
      ),
    );
  }

  /// 切换关注状态
  void _toggleFollow(String targetUserId) {
    if (_currentUser == null) return;

    final isCurrentlyFollowing = _followRoom.isFollowing(
      _currentUser!.id,
      targetUserId,
    );

    bool success;
    if (isCurrentlyFollowing) {
      success = _followRoom.performUnfollow(_currentUser!.id, targetUserId);
    } else {
      success = _followRoom.performFollow(_currentUser!.id, targetUserId);
    }

    if (success) {
      StageWhisper.cheer(
        isCurrentlyFollowing
            ? 'Unfollowed successfully'
            : 'Followed successfully',
      );
    } else {
      StageWhisper.lament('Operation failed');
    }
  }

  /// 跳转到用户主页
  void _navigateToUserProfile(BuildContext context, String userId) {
    context.router.push(OtherProfileProduction.query(userId: userId));
  }
}
